package com.yq;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class DFileList
{
    ArrayList<File> list = new ArrayList<File>();
    
    long fileSize;
    String lastName;
    public DFileList(long fileSize, File file) {
        this.fileSize = fileSize;
        this.lastName = getLastName(file.getName());
        add(file);
    }
    
    public static String getLastName(String name) {
        if (name == null || name.length() <= 2) {
            return "";
        }
        return name.substring(name.length() - 2);
    }
    
    public void add(File file) {
        for (int i = 0; i < list.size(); i++)
        {
            if (file.getPath().equals(list.get(i).getPath())) {
                return;
            }
        }
        list.add(file);
    }
    
    public boolean isDouble() {
        return list.size() > 1;
    }
    
    public String[] getList() {
        String[] rtn = new String[list.size()]; 
        for (int i = 0; i < rtn.length; i++)
        {
            rtn[i] = list.get(i).getPath();
        }
        return rtn;
    }
    
    public String getFirstName() {
        return list.get(0).getPath();
    }
    
    public void deleteFile(int index) {
        if (index < 0 || index >= list.size()) {
            return;
        }
        File file = list.get(index);
        if (!file.exists()) {
            return;
        }
        file.delete();
        list.remove(file);
        if (list.size() <= 1) {
            FileManage.getInstance().remove(this);
        }
        DoubleFile.instance.deleteUpdate();
        DoubleFile.instance.showMessage("删除文件" + file.getPath());
    }
    
    public int deleteAllFile() {
    	int count = 0;
    	while (list.size() > 1) {
    		File file = list.get(1);
            if (!file.exists()) {
                return count;
            }
            file.delete();
            count++;
            list.remove(file);
    	}
    	return count;
    }
    
    public void openFile(int index) {
        if (index < 0 || index >= list.size()) {
            return;
        }
        File file = list.get(index);
        if (file.exists()) {
            String[] cmd = new String[5];  
            cmd[0] = "cmd";  
            cmd[1] = "/c";  
            cmd[2] = "start";  
            cmd[3] = " ";  
            cmd[4] = file.getParent();  
            try
            {
                Runtime.getRuntime().exec(cmd);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            } 
        }
    }

    public File getIndex(int selectionIndex)
    {
        if (selectionIndex < 0 || selectionIndex >= list.size()) {
            return null;
        }
        return list.get(selectionIndex);
    }
}
